#include <iostream>
#include <vector>
#include <queue>

using namespace std;

// 102. 二叉树的层序遍历

// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        if(root == nullptr)
            return res;

        queue<TreeNode*> q;
        q.push(root);

        while(!q.empty()) {
            int levelSize = q.size();   // 这一行是关键，每次先获取当前队列的size，即为当前层
            vector<int> currentLevel;

            for(int i = 0; i < levelSize; i++) {
                TreeNode *currNode = q.front();
                q.pop();
                currentLevel.push_back(currNode->val);

                if(currNode->left)
                    q.push(currNode->left);
                if(currNode->right)
                    q.push(currNode->right);
            }
            res.push_back(currentLevel);
        }
        return res;
    }
};

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}
